<?php
// +----------------------------------------------------------------------
// | 众联TK架构 [ ZoomTk ]
// +----------------------------------------------------------------------
// | 版权所有 2017~2037 成都众联思索科技有限公司 [ http://www.zoomtk.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://www.sopvip.com
// +----------------------------------------------------------------------
// | 开源协议 ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\member\home;
use app\common\controller\Common;
use app\member\model\User as UserModel;
use think\Hook;

/**
 * 用户公开控制器，不经过权限认证
 * @package app\user\admin
 */
class Login extends Common
{
    /**
     * 用户登录
     * @author Sunday <153788231@qq.com>
     * @return mixed|void
     */
    public function login()
    {
        $url_return=$this->request->controller()!='Login'?cookie('__url_return__'):'mall/user.index/index';

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $rememberme = isset($data['remember-me']) ? true : false;

            // 登录钩子
            $hook_result = Hook::listen('login', $data);

            if (!empty($hook_result) && true !== $hook_result[0]) {
                $this->error($hook_result[0]);
            }

            // 验证数据
            $result = $this->validate($data, 'User.signin');
            if(true !== $result){
                // 验证失败 输出错误信息
                $this->error($result);
            }

            // 验证码
            if (config('captcha_signin')) {
                $captcha = $this->request->post('captcha', '');
                $captcha == '' && $this->error('请输入验证码');
                if(!captcha_check($captcha, '', config('captcha'))){
                    //验证失败
                    $this->error('验证码错误或失效');
                };
            }
            // 登录
            $UserModel = new UserModel;
            $uid = $UserModel->login($data['username'], $data['password'], $rememberme);
            if ($uid) {
                // 记录行为
                action_log('user_signin', 'member_user', $uid, $uid);
             //   var_dump($url_return);die;
                $this->success('登录成功', $url_return);
            } else {
                $this->error($UserModel->getError());
            }
        } else {
            return is_login() ? $this->redirect($url_return) : $this->fetch();
        }
    }

    /**
     * 退出登录
     * @author Sunday <153788231@qq.com>
     */
    public function signout()
    {
        session(null);
        cookie('uid', null);
        cookie('signin_token', null);
        return $this->redirect('login');
    }
}
